#include "http_server.h"
#include "qtch/hook.h"


namespace qtch {
namespace http {

static Logger::ptr logger = QTCH_LOG_NAME("system");

HttpServer::HttpServer(bool keeplive,qtch::IOManager* worker
              ,qtch::IOManager* ioWorker ,qtch::IOManager* acceptWorker)
    :TcpServer(worker,ioWorker,acceptWorker)
    ,m_isKeeplive(keeplive){
    m_dispatch.reset(new ServletDispath);
    m_type = "http";
}

void HttpServer::handleClient(Socket::ptr client){
    QTCH_LOG_DEBUG(logger) << "handleClient: " << client;
    HttpSession::ptr session(new HttpSession(client));
    do{
        HttpRequest::ptr req = session->recvRequest();
        if(!req){
            QTCH_LOG_DEBUG(logger) << "recv http request fail, errno="
                << errno << " errstr=" << strerror(errno)
                << " client:" << client << " keeplive=" << m_isKeeplive;
            break;
        }
        
        HttpResponse::ptr rsp(new HttpResponse(req->getVersion(), req->isClose() || !m_isKeeplive));
        rsp->setHeader("Server",getName());
        m_dispatch->handle(req,rsp,session);
        int rt = session->sendResponse(rsp);
        if(!m_isKeeplive || req->isClose() || rt<=0){
            break;
        }

    }while(true);
    session->close();
}




}
}